<?php

namespace app\admin\model\scanwork;

use think\Model;

class QualityStandard extends Model
{
    // 表名
    protected $name = 'scanwork_quality_standard';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
    ];
    
    public function getStatusList()
    {
        return ['0' => __('禁用'), '1' => __('启用')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 关联工序
    public function process()
    {
        return $this->belongsTo('app\admin\model\scanwork\Process', 'process_id', 'id');
    }

    // 关联产品
    public function product()
    {
        return $this->belongsTo('app\admin\model\scanwork\Product', 'product_id', 'id');
    }

    // 关联质检记录
    public function qualityRecords()
    {
        return $this->hasMany('app\admin\model\scanwork\QualityRecord', 'standard_id', 'id');
    }

    /**
     * 获取检查项目数组
     */
    public function getCheckItemsArray()
    {
        $checkItems = $this->check_items;
        if (is_string($checkItems)) {
            return json_decode($checkItems, true);
        }
        return $checkItems ?: [];
    }

    /**
     * 获取公差要求数组
     */
    public function getToleranceRequirementsArray()
    {
        $tolerance = $this->tolerance_requirements;
        if (is_string($tolerance)) {
            return json_decode($tolerance, true);
        }
        return $tolerance ?: [];
    }

    /**
     * 根据工序ID获取质检标准
     */
    public static function getByProcessId($processId)
    {
        return self::where('process_id', $processId)
            ->where('status', 1)
            ->find();
    }

    /**
     * 根据产品ID获取质检标准
     */
    public static function getByProductId($productId)
    {
        return self::where('product_id', $productId)
            ->where('status', 1)
            ->find();
    }

    /**
     * 获取通用质检标准
     */
    public static function getGeneralStandard()
    {
        return self::where('process_id', null)
            ->where('product_id', null)
            ->where('status', 1)
            ->find();
    }
}
